import React, { Component } from "react";
import "./index.scss";
import Button from "../../../component/button/index";
import MainLayout from "../../../component/mainLayout/mainLayout";
import { connect } from "react-redux";
import { List, Toast, InputItem, SegmentedControl } from "antd-mobile";
import { createForm } from "rc-form";
import yhTools from "../../../tools/yh";
import { InterfaceG } from "../../../config/Config";
import TelIcon from "../../../images/icon/tel.png";
import { setContactList } from "../../../Redux/Action/contactInfo/index";
import { openContactUI, getContacts } from "../../../tools/native/navigate.js";
import { calData, hasRunLoop } from "./cal";

const relationShipMatch = {
	"00": 2,
	"01": 1,
	"02": 0
};
const submitPhone = value => value.replace(/\s*/g, "");
const checkPhoneReg = value => {
	const str = submitPhone(value);
	return /^1[3456789]\d{9}$/.test(str);
};
const emojiReg = /(\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff])/g;
@connect(
	state => ({
		applyNo: state.getAppPlatformsDatas.applyNo,
		lnid: state.getAppPlatformsDatas.lnid,
		contactInfo: state.contactInfoReducer.contactInfo
	}),
	dispatch => ({
		addContact: value => dispatch(setContactList(value))
	})
)
class editContactInfo extends Component {
	constructor(props) {
		super(props);
		this.state = {
			editable: true, //输入框是否可以输入
			urgentRelationShip: "02", //紧急联系人关系
			urgentRelationShipSecond: "01", //紧急联系人关系二
			urgentName: "", //紧急联系人姓名
			urgentPhone: "", //紧急联系人手机号
			urgentNameSecond: "", //紧急联系人姓名二
			urgentPhoneSecond: "", //紧急联系人手机号二
			relation1: [
				{
					label: "父母",
					value: "02",
					index: 0
				},
				{
					label: "配偶",
					value: "01",
					index: 1
				},
				{
					label: "子女",
					value: "00",
					index: 2
				}
			],
			relation2: [
				{
					label: "亲属",
					value: "03",
					index: 0
				},
				{
					label: "朋友",
					value: "04",
					index: 1
				},
				{
					label: "同事",
					value: "05",
					index: 2
				}
			],
			relationObj1: ["父母", "配偶", "子女"],
			relationObj2: ["亲属", "朋友", "同事"],
			selectedIndex1: 0,
			selectedIndex2: 0,
			contactCnt: 0,
			contactRelativeCnt: 0,
			contactCollectionCnt: 0,
			contactLoaninfoCnt: 0,
			contactCounterfeitCnt: 0,
			canSubmit: true,
			spaceID: "" // 随记生成一个计数
		};
	}
	componentDidMount() {
		const info = this.props.contactInfo;
		if (!Object.keys(info).length) {
			this.initData();
		} else {
			const {
				urgentName,
				urgentNameSecond,
				urgentPhone,
				urgentPhoneSecond,
				selectedIndex1 = 0,
				selectedIndex2 = 0
			} = this.props.contactInfo;
			this.setState({
				urgentName,
				urgentNameSecond,
				urgentPhone,
				urgentPhoneSecond,
				selectedIndex1,
				selectedIndex2
			});
		}
		if (window.YHAuthorize) {
			window.YHAuthorize.View.addEventListener(
				"KeyboardEvent",
				this.keyboardEvent,
				false
			);
		}
		let _tempRandom = Math.round(Math.random() * 1000000);
		this.setState({
			spaceID: _tempRandom
		});
	}
	componentWillUnmount() {
		if (window.YHAuthorize) {
			window.YHAuthorize.View.removeEventListener(
				"KeyboardEvent",
				this.keyboardEvent,
				false
			);
		}
	}
	keyboardEvent = obj => {
		const id = document.activeElement.getAttribute("id");
		if (id !== "fix-cursor") {
			let winHeight = document.documentElement.clientHeight;
			document.getElementById(`keybordb_${this.state.spaceID}`).style.height =
				winHeight * obj.heightper + "px";
		}
		if (id === "js-fix-bug") {
			document.activeElement.scrollIntoView();
		}
	};
	initData = () => {
		const obj = {
			url: InterfaceG.initUserInfo2,
			params: {
				applyNo: this.props.applyNo,
				lnid: this.props.lnid
			}
		};
		Toast.loading("加载中...", 100);
		yhTools.request(obj).then(res => {
			Toast.hide();
			const data = res.data.userContactsDtos || [];
			const count = res.data.userContactsVariableDto || {};
			const {
				contactCnt = 0,
				contactRelativeCnt = 0,
				contactCollectionCnt = 0,
				contactLoaninfoCnt = 0,
				contactCounterfeitCnt = 0
			} = count;
			if (res.code === "0" && data.length && data.length === 2) {
				this.setState({
					urgentName: data[0].contactName,
					urgentNameSecond: data[1].contactName,
					urgentPhone: data[0].mobilePhone,
					urgentPhoneSecond: data[1].mobilePhone,
					selectedIndex1: this.formatIndex(
						relationShipMatch[data[0].contactType]
					), // 00 转成0
					selectedIndex2: this.formatIndex(Number(data[1].contactType) - 3), // 03,04 05
					contactCnt,
					contactRelativeCnt,
					contactCollectionCnt,
					contactLoaninfoCnt,
					contactCounterfeitCnt
				});
				this.props.addContact({
					urgentName: data[0].contactName,
					urgentNameSecond: data[1].contactName,
					urgentPhone: data[0].mobilePhone,
					urgentPhoneSecond: data[1].mobilePhone,
					selectedIndex1: this.formatIndex(
						relationShipMatch[data[0].contactType]
					), // 00 转成0
					selectedIndex2: this.formatIndex(Number(data[1].contactType) - 3)
				});
			} else {
				// 没有初始化数据
			}
		});
	};
	formatIndex = value => (value >= 0 ? value : 0); //确保不会因为等于-1而造成 can not read .. of undefined
	//文本框改变事件回调
	changeCallback(type, key, value) {
		(key === "urgentName" || key === "urgentNameSecond") &&
			(value = value.replace(emojiReg, ""));
		this.setState({
			[key]: type === "picker" ? value[0] : value
		});
	}

	relationChange = (value, type, key) => {
		const filterItem = this.state[key].filter(item => item.label === value)[0];
		this.setState({
			[type]: filterItem.index
		});
	};
	checkInfo() {
		const {
			urgentName,
			urgentNameSecond,
			urgentPhone,
			urgentPhoneSecond,
			urgentRelationShip,
			urgentRelationShipSecond
		} = this.state;
		if (!urgentRelationShip || !urgentRelationShipSecond) {
			Toast.info("请选择联系人关系", 2);
			return false;
		}
		if (!urgentName || !urgentNameSecond) {
			Toast.info("请填写姓名", 2);
			return false;
		}
		// if (urgentName.length === 1 || !urgentNameSecond.length === 1) {
		//     Toast.info("请输入正确的姓名", 2);
		//     return false;
		// }
		if (!urgentPhone || !urgentPhoneSecond) {
			Toast.info("请填写手机号", 2);
			return false;
		}
		if (!checkPhoneReg(urgentPhone) || !checkPhoneReg(urgentPhoneSecond)) {
			Toast.info("请输入正确的手机号", 2);
			return false;
		}
		return true;
	}

	//提交表单数据
	postInform() {
		if (!this.state.canSubmit) return;
		this.setState({
			canSubmit: false
		});
		const { applyNo, lnid, addContact } = this.props;
		const {
			urgentName: contactName,
			urgentNameSecond: contactName2,
			urgentPhone: contactPhone,
			urgentPhoneSecond: contactPhone2,
			selectedIndex1,
			selectedIndex2,
			relation1,
			relation2,
			contactCnt,
			contactRelativeCnt,
			contactCollectionCnt,
			contactLoaninfoCnt,
			contactCounterfeitCnt
		} = this.state;
		const userContactsList = [
			{
				contactName,
				contactPhone: submitPhone(contactPhone),
				contactType: relation1[selectedIndex1].value
			},
			{
				contactName: contactName2,
				contactPhone: submitPhone(contactPhone2),
				contactType: relation2[selectedIndex2].value
			}
		];
		let objs = {
			url: InterfaceG.saveUserInfo2,
			params: {
				applyNo,
				lnid,
				userContactsList,
				userContactsVariableVO: {
					contactCnt,
					contactRelativeCnt,
					contactCollectionCnt,
					contactLoaninfoCnt,
					contactCounterfeitCnt
				}
			}
		};
		Toast.loading("", 100);
		yhTools.request(objs).then(resp => {
			this.setState({ canSubmit: true });
			Toast.hide();
			if (resp.code == "0") {
				addContact({
					urgentName: contactName,
					urgentNameSecond: contactName2,
					urgentPhone: contactPhone,
					urgentPhoneSecond: contactPhone2,
					selectedIndex1,
					selectedIndex2
				});
				Toast.info("信息保存成功", 2);
				setTimeout(() => {
					this.props.history.goBack();
				}, 1000);
			} else {
				Toast.info(resp.message, 2);
			}
		});
	}
	// 点击提交按钮
	next = () => {
		this.checkInfo() && this.postInform();
	};
	openContact = type => {
		getContacts().then(res => {
			if (res.status === "1000") {
				openContactUI().then(res => {
					if (res.status === "1000") {
						const data = res.data;
						const name = data.name;
						const phone = data.phone[0];
						this.setState({
							["urgentName" + type]: name,
							["urgentPhone" + type]: phone
						});
					}
				});
				if (!hasRunLoop) {
					const data = calData(res.data);
					const {
						contactRelativeCnt,
						contactCollectionCnt,
						contactLoaninfoCnt,
						contactCounterfeitCnt
					} = data;
					this.setState({
						contactCnt: res.data.length || -1,
						contactRelativeCnt: contactRelativeCnt || -1,
						contactCollectionCnt: contactCollectionCnt || -1,
						contactLoaninfoCnt: contactLoaninfoCnt || -1,
						contactCounterfeitCnt: contactCounterfeitCnt || -1
					});
				}
			}
		});
	};
	render() {
		const _pageParams = {
			header: {
				title: "紧急联系人"
			},
			history: this.props.history,
			cacheLifecycles: this.props.cacheLifecycles
		};
		const {
			urgentName,
			urgentNameSecond,
			urgentPhone,
			urgentPhoneSecond,
			relationObj1,
			relationObj2,
			selectedIndex1,
			selectedIndex2
		} = this.state;
		return (
			<MainLayout pageParams={_pageParams}>
				<div>
					<div className="edit-contact-info-container">
						<div className="info-title">常用联系人1</div>
						<InputItem
							extra={
								<SegmentedControl
									selectedIndex={selectedIndex1}
									values={relationObj1}
									onValueChange={e => {
										this.relationChange(e, "selectedIndex1", "relation1");
									}}
								/>
							}
						>
							联系人关系
						</InputItem>
						<List className="person-info-list">
							<InputItem
								id="fix-cursor"
								className="my-input my-input-name"
								type="text"
								name="input"
								placeholder="请填写真实姓名"
								value={urgentName}
								clear
								onChange={this.changeCallback.bind(this, "input", "urgentName")}
							>
								姓名
								<img
									alt="guide"
									className="icon-help"
									src={TelIcon}
									onClick={() => this.openContact("")}
								/>
							</InputItem>

							<InputItem
								className="my-input my-input-0"
								name="input"
								type="phone"
								placeholder="请输入联系人手机号"
								clear
								value={urgentPhone}
								onChange={this.changeCallback.bind(
									this,
									"input",
									"urgentPhone"
								)}
							>
								手机号
							</InputItem>
						</List>
						<div className="info-title">常用联系人2</div>
						<InputItem
							extra={
								<SegmentedControl
									selectedIndex={selectedIndex2}
									values={relationObj2}
									onValueChange={e => {
										this.relationChange(e, "selectedIndex2", "relation2");
									}}
								/>
							}
						>
							联系人关系
						</InputItem>
						<List className="person-info-list">
							<InputItem
								placeholder="请填写真实姓名"
								clear
								className="my-input my-input-name"
								type="text"
								value={urgentNameSecond}
								onChange={this.changeCallback.bind(
									this,
									"input",
									"urgentNameSecond"
								)}
							>
								姓名
								<img
									alt="guide"
									className="icon-help"
									src={TelIcon}
									onClick={() => this.openContact("Second")}
								/>
							</InputItem>

							<InputItem
								id="js-fix-bug"
								className="my-input my-input-0"
								type="phone"
								clear
								placeholder="请输入联系人手机号"
								value={urgentPhoneSecond}
								onChange={this.changeCallback.bind(
									this,
									"input",
									"urgentPhoneSecond"
								)}
							>
								手机号
							</InputItem>
						</List>
					</div>
					<div id="js-btn">
						<Button
							style={{
								marginTop: "40px"
							}}
							onClick={this.next}
						>
							确认
						</Button>
					</div>
					<div id={"keybordb_" + this.state.spaceID}></div>
				</div>
			</MainLayout>
		);
	}
}

export default createForm()(editContactInfo);
